package com.nhim.cms.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nhim.cms.domain.ElementDefinition;
import com.nhim.cms.util.ElementDefinitionManager;
import com.nhim.core.AppContext;

public class CMSHelper {

	private static final Pattern TYPE_REGEX = Pattern.compile(
			"type\\s*=\\s*[\"'](.*?)[\"']", Pattern.CASE_INSENSITIVE);
	private static final Pattern NAME_REGEX = Pattern.compile(
			"name\\s*=\\s*[\"'](.*?)[\"']", Pattern.CASE_INSENSITIVE);

	private static String getType(String text) {
		Matcher matcher = TYPE_REGEX.matcher(text);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";
	}
	private static String getName(String text)
	{
		Matcher matcher = NAME_REGEX.matcher(text);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";
	}

	public static String processTag(String tag) {
		String result = "";
		String type = getType(tag);
		if ("".equals(type))
			return tag;

		try {
			switch (ItemType.valueOf(type.toUpperCase())) {
			case CUSTOMWIDGET:
				result = processCustomWidget(tag);
				break;
			case FLEXTABLE:
				result = processFlextTable(tag);
				break;
			case ELEMENT:
				result = processElement(tag);
				break;

			}
			return result;

		} catch (Exception ex) {
			return tag;
		}

	}

	private static String processElement(String tag) {

		String name = getName(tag);
		if("".equals(name))
				return tag;
		ElementDefinitionManager elementManager = ElementDefinitionManager.getFromApplicationContext(AppContext.getApplicationContext());
		ElementDefinition element = elementManager.findByName(name);
		if(element == null)
			return "<!-- can not find element name: " + name + "-->";
		return processElement(tag,element);
		
	}
	private static String processElement(String tag,ElementDefinition element)
	{
		return tag;
		
	}

	private static String processFlextTable(String tag) {

		return "FlexTable";
	}

	private static String processCustomWidget(String tag) {

		return "Resource";
	}


}
